<template>
  <!-- 面包屑导航区域 -->
  <breadcrumb :childMenu="['权限管理', '角色管理']" />
  <!-- 卡片视图 -->
  <el-card>
    <el-row>
      <!-- 添加角色按钮 -->
      <el-button type="primary" @click="addDialogVisible = true"
        >添加角色</el-button
      >
    </el-row>
    <!-- 角色列表区域 -->
    <el-table :data="roleList" stripe border size="mini">
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template v-slot="scope">
          <el-row
            v-for="(item1, index1) in scope.row.children"
            :key="item1.id"
            :class="{ bdtop: true, bdbottom: index1 === 0, vcenter: true }"
          >
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag
                closable
                @close="removePermissionById(scope.row, item1.id)"
                >{{ item1.authName }}</el-tag
              >
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级和三级权限 -->
            <el-col :span="19">
              <!-- 通过for循环嵌套渲染二级权限 -->
              <el-row
                :class="{ bdtop: index2 !== 0, vcenter: true }"
                v-for="(item2, index2) in item1.children"
                :key="item2.id"
              >
                <el-col :span="6" type="success">
                  <el-tag
                    closable
                    @close="removePermissionById(scope.row, item2.id)"
                    >{{ item2.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag
                    v-for="(item3, index3) in item2.children"
                    type="warning"
                    :key="item3.id"
                    closable
                    @close="removePermissionById(scope.row, item3.id)"
                    >{{ item3.authName }}</el-tag
                  >
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column label="序号" type="index"> </el-table-column>
      <el-table-column label="角色名称" prop="roleName"> </el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
      <el-table-column label="是否启用" prop="isActive">
        <template v-slot="prop">
          <el-tag v-if="prop.row.isActive === true">是 </el-tag>
          <el-tag v-if="prop.row.isActive === false" type="info">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300px">
        <template v-slot="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.id)"
          >
            编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteRoleById(scope.row.id)"
          >
            删除</el-button
          >
          <el-button
            type="warning"
            icon="el-icon-setting"
            size="mini"
            @click="showSetPermissionDialog(scope.row)"
            >分配权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 添加角色的表单对话框 -->
  <add-role-form
    :addDialogVisible="addDialogVisible"
    :addFromRules="formRules"
    @addDialogClose="addDialogClose"
  />
  <!-- 修改角色的表单对话框 -->
  <edit-role-form
    :editDialogVisible="editDialogVisible"
    :editForm="editForm"
    :editFormRules="formRules"
    @editDialogClose="editDialogClose"
  />
  <!-- 分配权限的对话框 -->
  <set-permission-dialog
    :setPermissionDialogVisible="setPermissionDialogVisible"
    :permissionList="permissionList"
    :defKeys="defKeys"
    :roleId="roleId"
    @setPermissionDialogClose="setPermissionDialogClose"
  ></set-permission-dialog>
</template>

<script>
import Breadcrumb from "@/common/Breadcrumb.vue";
import AddRoleForm from "./childComponents/AddRoleForm.vue";
import EditRoleForm from "./childComponents/EditRoleForm.vue";
import SetPermissionDialog from "./childComponents/SetPermissionDialog.vue";
import {
  getRoleList,
  deleteRoleById,
  getRoleInfo,
  removePermissionById
} from "network/role.js";
import { getMenus } from "network/permissions.js";
export default {
  components: {
    Breadcrumb,
    AddRoleForm,
    EditRoleForm,
    SetPermissionDialog
  },
  data() {
    return {
      // 表单的验证规则对象
      formRules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "角色名的长度在3~10个字符之间",
            trigger: "blur"
          }
        ],
        roleDesc: [
          { required: false, message: "请输入角色描述", trigger: "blur" },
          {
            max: 100,
            message: "角色的最大长度为100个字符之间",
            trigger: "blur"
          }
        ]
      },
      //所有角色的列表数据
      roleList: [],
      //保存查询到的角色信息对象
      editForm: {},
      //显示隐藏添加角色对话框
      addDialogVisible: false,
      //显示隐藏修改角色的对话框
      editDialogVisible: false,
      //显示隐藏设置权限的对话框
      setPermissionDialogVisible: false,
      //所有权限的数据
      permissionList: [],
      //分配权限对话框默认选中节点
      defKeys: [],
      //角色Id
      roleId: ""
    };
  },
  created() {
    this.getRoleLit();
  },
  methods: {
    //加载角色列表数据
    async getRoleLit() {
      const res = await getRoleList();
      if (!res.success)
        return this.$message.error({ showClose: true, message: res.msg });
      this.roleList = res.response;
    },
    // 展示编辑对话框
    async showEditDialog(id) {
      const res = await getRoleInfo(id);
      if (!res.status)
        return this.$message.error({ showClose: true, msg: res.messgae });
      this.editForm = res.response;
      this.editDialogVisible = true;
    },
    //添加新角色对话框关闭
    addDialogClose(isReload) {
      this.addDialogVisible = false;
      if (isReload) this.getRoleLit();
    },
    //修改角色对话框关闭
    editDialogClose(isReload) {
      this.editDialogVisible = false;
      if (isReload) this.getRoleLit();
    },
    //删除角色
    async deleteRoleById(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          //如果角色确定删除,则返回值为字符串'confirm'
          const res = await deleteRoleById(id);
          if (res.status === 200) {
            this.$message.success({
              showClose: true,
              message: res.msg
            });
            return this.getRoleLit();
          } else
            return this.$message.error({
              showClose: true,
              message: res.msg
            });
        })
        .catch(() => {
          //如果角色取消了删除,则返回值为字符串'cancel'
          this.$message.info({
            showClose: true,
            message: "已取消删除!"
          });
        });
    },
    //展示分配权限的对话框
    async showSetPermissionDialog(role) {
      const res = await getMenus("tree");
      if (!res.success)
        return this.$message.error({ showClose: true, message: res.msg });
      //数据赋值
      this.permissionList = res.response;
      if (role.children.length > 0) {
        //递归获得所有末级节点的id
        role.children.forEach(item => this.getLeafKeys(item, this.defKeys));
      }
      // console.log(this.defKeys);
      this.roleId = role.id;
      this.setPermissionDialogVisible = true;
    },
    //分配权限对话框关闭
    setPermissionDialogClose(isReload) {
      this.defKeys = [];
      this.setPermissionDialogVisible = false;
      if (isReload) this.getRoleLit();
    },
    //递归获得所有末级节点的id
    getLeafKeys(node, arr) {
      //如果当前节点不包含children属性,则是末级节点
      if (node.children.length === 0) return arr.push(node.id);
      node.children.forEach(item => this.getLeafKeys(item, arr));
    },
    //根据id移除角色对应的权限
    async removePermissionById(role, permissionId) {
      //弹窗提示用户是否要删除
      const confirmResult = await this.$confirm("确定要删除此权限吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err);
      if (confirmResult !== "confirm") return this.$message.info("取消了删除!");
      const res = await removePermissionById(role.id, permissionId);
      if (!res.success)
        return this.$message.error({ showClose: true, message: res.msg });
      //利用vue的响应式原理,刷新当年操作数据
      // this.getRoleLit()
      role.children = res.response.children;
    }
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
